import { getUserType } from '@/utils/storage'

/** 判断参数是否定义 */
export const isDef = p => p !== undefined && p !== null

/** 根据 userType 决定重定向页面 */
export function redirectToHome() {
  // userType: 0-游客；1-员工
  const userType = getUserType()

  if (userType === 0) {
    uni.redirectTo({ url: '/package-guest/pages/index/index' })
  } else if (userType === 1) {
    uni.switchTab({ url: '/pages/home/index/index' })
  }
}

export function sleep(time) {
  if (typeof time !== 'number') {
    return
  }
  return new Promise(resolve => setTimeout(resolve, time))
}

/**
* 显示消息提示框
* @param content 提示的标题
* @param duration 持续时长，单位毫秒
*/
export function toast(content, duration = 1500) {
  uni.showToast({
    icon: 'none',
    title: content,
    duration,
  })
}

/**
* 显示确认弹窗
* @param content 提示的内容
* @param title 标题
* @example
  ```js
  showConfirm('确认删除吗？', '警告').then(() => {
    // 调用删除接口
  })

  // or

  await showConfirm('确认删除吗？', '警告')
  // 调用删除接口
  ```
*/
export function showConfirm(content, title = '提示') {
  return new Promise((resolve, reject) => {
    uni.showModal({
      title,
      content,
      cancelText: '取消',
      confirmText: '确定',
      complete: (res) => {
        if (res.confirm) {
          resolve()
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

/**
* 参数处理
* @param params 参数
*/
export function tansParams(params) {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName]
    const part = `${encodeURIComponent(propName)}=`
    if (value !== null && value !== '' && typeof (value) !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof (value[key]) !== 'undefined') {
            const params = `${propName}[${key}]`
            const subPart = `${encodeURIComponent(params)}=`
            result += `${subPart + encodeURIComponent(value[key])}&`
          }
        }
      } else {
        result += `${part + encodeURIComponent(value)}&`
      }
    }
  }
  return result
}
